#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import argparse
import logging
import logging.config
import tornado.web
import tornado.httpserver

from config import MdConfig
from handler.sms import Handler, SmsHandler
from handler.wechat import WechatHandler
from handler.user import LoginHandler, RegistHandler, UserHandler
from handler.news import AdvertHandler, NewsHandler


class Application(tornado.web.Application):
    def __init__(self, config):
        handlers = [
            (r"/", Handler),
            (r"/sms/notify", SmsHandler),
            (r"/mp/all", WechatHandler),
            (r"/wechat/update", WechatHandler),
            (r"/user/login", LoginHandler),
            (r"/user/regist", RegistHandler),
            (r"/user/query", UserHandler),
            (r"/news", NewsHandler),
            (r"/adverts", AdvertHandler)
        ]
        self.db = config.get_mdb()
        self.rds = config.get_rds()
        tornado.web.Application.__init__(self, handlers, debug=True)
        logging.info('new app instance')


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--config', help='配置文件', default='conf/server.conf')
    parser.add_argument('--logging', help='日志配置', default='conf/logging.conf')
    args = parser.parse_args()

    if args.logging:
        os.makedirs('log', exist_ok=True)
        logging.config.fileConfig(args.logging)

    config = MdConfig(args.config)

    http_server = tornado.httpserver.HTTPServer(Application(config))
    http_server.listen(config.listen_port)
    logging.info('listen {0}'.format(config.listen_port))
    tornado.ioloop.IOLoop.instance().start()

    # 添加退出信号处理
    logging.info('vue server exit.')


if __name__ == '__main__':
    main()
